import datetime
import uuid
from decimal import Decimal

from django.contrib.auth.hashers import make_password, check_password
from django.shortcuts import render

# Create your views here.
from rest_framework import viewsets
from rest_framework.response import Response
from rest_framework.views import APIView

from apps.User.serlizers import chepanserlizer, getchepanserlizer, Infoserlizer, INofgetserlizer, Userinfoserlizer
from firepark_admin.models import Userinfo, Plate, Info


def create_user(phone, password, today_time):
    password = make_password(password, None, 'pbkdf2_sha256')
    Userinfo.objects.create(phone=phone, password=password, create_time=today_time, balance=0, flag=True,
                            update_time=today_time).save()


def user_confirm(user_name, password):
    results = Userinfo.objects.filter(phone__exact=user_name).values()
    if check_password(password, results[0].get('password')):
        return True
    else:
        return False


class Register(APIView):
    def post(self, request, *args, **kwargs):
        print(request.data)
        phone = request.data.get("username")
        print("注册请求")
        password = request.data.get("password")
        if Userinfo.objects.filter(phone=phone).exists():
            return Response({"status": 202, "message": "此用户已经被注册"})
        else:
            today_time = str(datetime.datetime.now()).split('.')[0]
            print(today_time)
            today_time = datetime.datetime.strptime(today_time, '%Y-%m-%d %H:%M:%S')
            create_user(phone, password, today_time)
            return Response({"status": 200})


class Loginviw(APIView):
    def post(self, request, *args, **kwargs):
        phone = request.data.get("username")
        print("登录请求")
        password = request.data.get("password")
        if user_confirm(phone, password):
            shuu = Userinfo.objects.filter(phone=phone).first()
            tokens = uuid.uuid4()
            shuu.token = tokens
            shuu.save()
            return Response({"status": 200, "token": tokens})
        return Response({"status": 203})


class chepanviewset(viewsets.ModelViewSet):
    queryset = Plate.objects.all()

    def get_serializer_class(self):
        if self.action == "create":
            print("添加车牌")
            a = chepanserlizer
            return a
        else:
            b = getchepanserlizer
            return b

    def list(self, request, *args, **kwargs):
        # print(request.query_params)
        tokens = request.query_params['token']
        s = Userinfo.objects.filter(token=tokens).first()
        print(s)
        queryset = self.filter_queryset(self.get_queryset().filter(users_id=s))
        print(queryset)

        page = self.paginate_queryset(queryset)
        if page is not None:
            serializer = self.get_serializer(page, many=True)
            return self.get_paginated_response(serializer.data)

        serializer = self.get_serializer(queryset, many=True)
        return Response(serializer.data)


class Updatepassword(APIView):
    def post(self, request, *args, **kwargs):
        password0 = request.data.get("password0")
        password1 = request.data.get("password")
        password2 = request.data.get("password1")
        token = request.data.get("token")
        obj = Userinfo.objects.filter(token=token).first()
        if user_confirm(obj.phone, password0) is False:
            return Response({"status": 204, "message": "不一致"})
        if password2 != password1:
            return Response({"status": 203, "message": "不一致"})
        obj.password = make_password(password1, None, 'pbkdf2_sha256')
        obj.save()
        return Response({"status": 200})


class recharge(APIView):
    def post(self, request, *args, **kwargs):
        password = request.data.get("password")
        number = request.data.get("number")
        token = request.data.get("token")
        obj = Userinfo.objects.filter(token=token).first()
        if user_confirm(obj.phone, password):
            obj.balance = obj.balance + Decimal(int(number))
            obj.save()
            return Response({"status": 200})
        else:
            return Response({"status": 203, "message": "密码错误"})


class Infoviewset(viewsets.ModelViewSet):
    serializer_class = Infoserlizer
    queryset = Info.objects.all()

    def get_serializer_class(self):
        print(self.action)
        if self.action == "create":
            a = Infoserlizer
            return a
        elif self.action == "list":
            return INofgetserlizer

    def list(self, request, *args, **kwargs):
        # print(request.query_params)
        tokens = request.query_params['token']
        s = Userinfo.objects.filter(token=tokens).first()
        print(s)
        queryset = self.filter_queryset(self.get_queryset().filter(name=s))
        page = self.paginate_queryset(queryset)
        if page is not None:
            serializer = self.get_serializer(page, many=True)
            return self.get_paginated_response(serializer.data)
        serializer = self.get_serializer(queryset, many=True)
        return Response(serializer.data)


class Userinfoviewset(viewsets.ModelViewSet):
    queryset = Userinfo.objects.all()
    serializer_class = Userinfoserlizer

    def list(self, request, *args, **kwargs):
        # print(request.query_params)
        tokens = request.query_params['token']
        queryset = self.filter_queryset(self.get_queryset().filter(token=tokens))
        page = self.paginate_queryset(queryset)
        if page is not None:
            serializer = self.get_serializer(page, many=True)
            return self.get_paginated_response(serializer.data)

        serializer = self.get_serializer(queryset, many=True)
        return Response(serializer.data)
